package handler

import (
	"fmt"
	"strconv"
	"trader/apps/common/resp"
	"trader/models"

	"github.com/gin-gonic/gin"
	"xorm.io/xorm"
)

type AccountHandler struct {
	Engine *xorm.Engine
}

func NewAccountHandler(engine *xorm.Engine) *AccountHandler {
	return &AccountHandler{Engine: engine}
}

func (h *AccountHandler) List(c *gin.Context) {
	userId := c.GetInt64("userId")

	d := make([]models.TradingAccount, 0)
	err := h.Engine.Where("user_id = ?", userId).Find(&d)
	if err != nil {
		resp.Fail(c, err)
		return
	}

	resp.OK(c, c.GetString("username"), d)
}

type AccountCreateRequest struct {
	Name   string `json:"name" binding:"required,min=4,max=20"`
	Remark string `json:"remark" binding:"omitempty,max=20"`
}

func (h *AccountHandler) Create(c *gin.Context) {
	var req AccountCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		resp.FailParam(c, fmt.Errorf("请求参数不合法: %v", err))
		return
	}

	userId := c.GetInt64("userId")
	exist, _ := h.Engine.Where("user_id=? and name=?", userId, req.Name).Exist(new(models.TradingAccount))
	if exist {
		resp.FailParam(c, fmt.Errorf("名称已存在"))
		return
	}

	newAccount := models.TradingAccount{
		UserId: userId,
		Name:   req.Name,
		Remark: req.Remark,
	}

	_, err := h.Engine.InsertOne(newAccount)
	if err != nil {
		resp.Fail(c, err)
		return
	}

	resp.OKWithoutData(c, "创建成功")
}

type AccountUpdateRequest struct {
	Name   string `json:"name" binding:"required,min=4,max=20"`
	Remark string `json:"remark" binding:"omitempty,max=20"`
}

func (h *AccountHandler) Update(c *gin.Context) {
	var err error
	id, err := strconv.ParseInt(c.Param("trading_account_id"), 10, 64)
	if err != nil {
		resp.FailParamf(c, "无效的参数")
		return
	}

	var req AccountUpdateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		resp.FailParam(c, fmt.Errorf("请求参数不合法: %v", err))
		return
	}

	userId := c.GetInt64("userId")
	exist, _ := h.Engine.Where("user_id=? and id != ? and name=?", userId, id, req.Name).Exist(new(models.TradingAccount))
	if exist {
		resp.FailParam(c, fmt.Errorf("名称已存在"))
		return
	}

	_, err = h.Engine.Table(new(models.TradingAccount)).ID(id).
		Cols("name", "remark").
		Update(map[string]interface{}{"remark": req.Remark, "name": req.Name})
	if err != nil {
		resp.FailDB(c, err)
		return
	}

	resp.OKWithoutData(c, "更新成功")
}

func (h *AccountHandler) Delete(c *gin.Context) {
	var err error
	id, err := strconv.ParseInt(c.Param("trading_account_id"), 10, 64)
	if err != nil {
		resp.FailParamf(c, "无效的参数")
		return
	}
	resp.Fail(c, fmt.Errorf("还未支持删除：%v", id))
}

func (h *AccountHandler) SetDefault(c *gin.Context) {
	var err error
	id, err := strconv.ParseInt(c.Param("trading_account_id"), 10, 64)
	if err != nil {
		resp.FailParamf(c, "无效的参数")
		return
	}

	userId := c.GetInt64("userId")
	session := h.Engine.NewSession()
	_ = session.Begin()
	_, err = session.Table(new(models.TradingAccount)).Where("user_id=? and is_default=?", userId, true).Cols("is_default").Update(map[string]interface{}{"is_default": false})
	if err != nil {
		_ = session.Rollback()
		resp.FailDB(c, err)
	}
	_, err = session.Table(new(models.TradingAccount)).Where("id=? and user_id=?", id, userId).Cols("is_default").Update(map[string]interface{}{"is_default": true})
	if err != nil {
		_ = session.Rollback()
		resp.FailDB(c, err)
		return
	}
	err = session.Commit()
	if err != nil {
		resp.FailDB(c, err)
		return
	}

	resp.OKWithoutData(c, "设置成功")
}
